/*
 * StopWatch.cs
 * 
 * Copyright (c) 2003-2004, dnAnalytics Project. All rights reserved.
 * Contributed by Richard Lyon.
*/

using System;
using System.Diagnostics;

namespace dnA.Utility{
	/// <summary>
	/// A simple stop watch class.
	/// </summary>
	class StopWatch {

		#region Fields

		/// <summary>The tics reading when start was called.</summary>
		private TimeSpan start = new TimeSpan(0);
		
		/// <summary>The tics reading when stop was called.</summary>
		private TimeSpan stop = new TimeSpan(0);

		/// <summary>Flag to indicate if stopwatch timing or is inactive.</summary>
		bool active;

		#endregion Fields

		#region Public Members
		/// <summary>Default constructor</summary>
		public StopWatch() {}

		/// <summary>Start StopWatch timing.</summary>
		/// <remarks>Resets the start value if the StopWatch is already started.</remarks>
		public void Start() {
			if (active == false) {
				active = true;
			}
			start = Process.GetCurrentProcess().UserProcessorTime;
		}

		///<summary>Retrieve the current processor time used by the process since it was started.</summary>
		///<returns>The processor time used by the process since it was started.</returns>
		public TimeSpan Current() {
			TimeSpan result;
			if( active ){
				result = Process.GetCurrentProcess().UserProcessorTime - start;
			}else{
				result = stop - start;
			}
			return result;
		}

		///<summary>Halt the StopWatch.</summary>
		///<returns>The processor time used by the process since it was started.</returns>
		public TimeSpan Stop() {
			TimeSpan result;
			if (active == true) {
				active = false;
				result = Process.GetCurrentProcess().UserProcessorTime - start;
			} else{
				result = stop - start;
			}
			return result;
		}
		#endregion Public Members
	}
}
